#!/bin/bash

# 小智ESP32服务器端 - Conda服务条款修复脚本
# 用于解决 "Terms of Service have not been accepted" 错误

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "请使用sudo运行此脚本"
        exit 1
    fi
}

# 修复conda服务条款问题
fix_conda_tos() {
    log_info "正在修复Conda服务条款问题..."
    
    # 检查conda是否可用
    if ! command -v conda &> /dev/null; then
        # 尝试添加conda到PATH
        if [[ -d "/opt/miniconda3" ]]; then
            export PATH="/opt/miniconda3/bin:$PATH"
        else
            log_error "未找到Conda安装，请先运行 sudo ./install_deps.sh"
            exit 1
        fi
    fi
    
    # 初始化conda
    if [[ -f "/opt/miniconda3/etc/profile.d/conda.sh" ]]; then
        source /opt/miniconda3/etc/profile.d/conda.sh
    fi
    
    # 接受服务条款
    log_info "正在接受Conda服务条款..."
    
    # 方法1：使用conda tos命令
    if conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main --channel https://repo.anaconda.com/pkgs/r 2>/dev/null; then
        log_success "服务条款已通过conda tos命令接受"
    else
        log_warning "conda tos命令失败，尝试其他方法..."
        
        # 方法2：手动创建配置文件
        local conda_config_dir="/root/.conda"
        mkdir -p "$conda_config_dir"
        
        cat > "$conda_config_dir/.condarc" << EOF
channels:
  - defaults
  - conda-forge
channel_priority: flexible
auto_activate_base: false
EOF
        
        log_info "已创建conda配置文件"
        
        # 方法3：使用--yes标志强制接受
        if conda config --set channel_priority flexible 2>/dev/null; then
            log_success "已设置conda配置"
        fi
    fi
    
    # 验证修复
    log_info "正在验证修复结果..."
    
    # 测试创建环境
    if conda create -n test-env python=3.10 -y --dry-run 2>/dev/null; then
        log_success "Conda服务条款问题已修复"
        return 0
    else
        log_warning "仍然存在问题，尝试最终解决方案..."
        
        # 最终方案：设置环境变量
        export CONDA_ALWAYS_YES=true
        export CONDA_CHANNEL_PRIORITY=flexible
        
        # 添加到系统环境
        echo 'export CONDA_ALWAYS_YES=true' >> /etc/environment
        echo 'export CONDA_CHANNEL_PRIORITY=flexible' >> /etc/environment
        
        log_success "已设置环境变量，请重新运行安装脚本"
    fi
}

# 创建xiaozhi-server环境
create_xiaozhi_env() {
    log_info "正在创建xiaozhi-server conda环境..."
    
    # 初始化conda
    if [[ -f "/opt/miniconda3/etc/profile.d/conda.sh" ]]; then
        source /opt/miniconda3/etc/profile.d/conda.sh
    fi
    
    # 检查环境是否已存在
    if conda env list | grep -q "xiaozhi-server"; then
        log_success "xiaozhi-server环境已存在"
        return 0
    fi
    
    # 设置环境变量
    export CONDA_ALWAYS_YES=true
    export CONDA_CHANNEL_PRIORITY=flexible
    
    # 创建环境
    conda create -n xiaozhi-server python=3.10 -y || {
        log_error "创建conda环境失败"
        exit 1
    }
    
    log_success "xiaozhi-server环境创建成功"
}

# 安装Python依赖
install_python_deps() {
    log_info "正在安装Python依赖..."
    
    local project_path="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    local requirements_file="$project_path/requirements.txt"
    
    if [[ ! -f "$requirements_file" ]]; then
        log_error "未找到requirements.txt文件: $requirements_file"
        exit 1
    fi
    
    # 初始化conda并激活环境
    source /opt/miniconda3/etc/profile.d/conda.sh
    conda activate xiaozhi-server
    
    # 升级pip
    pip install --upgrade pip
    
    # 安装依赖
    pip install -r "$requirements_file" || {
        log_error "安装Python依赖失败"
        exit 1
    }
    
    log_success "Python依赖安装完成"
}

# 主函数
main() {
    echo "========================================"
    echo "小智ESP32服务器端 - Conda服务条款修复"
    echo "========================================"
    echo ""
    echo "🔧 修复内容："
    echo "- 自动接受Conda服务条款"
    echo "- 创建xiaozhi-server环境"
    echo "- 安装Python依赖"
    echo "========================================"
    
    check_root
    fix_conda_tos
    create_xiaozhi_env
    install_python_deps
    
    echo "========================================"
    log_success "Conda服务条款修复完成！"
    echo "========================================"
    echo ""
    echo "📋 后续操作："
    echo "1. 重新运行: sudo ./install_deps.sh"
    echo "2. 或者直接启动服务: sudo systemctl start xiaozhi-server"
    echo "3. 查看状态: sudo systemctl status xiaozhi-server"
    echo "========================================"
}

# 错误处理
trap 'log_error "脚本执行失败，请检查错误信息"; exit 1' ERR

# 运行主函数
main "$@"